import { formatOptions, formatSeriesLabelToPercent, legendStyle } from './formatter';
import type { Options, BaseNameValueObject } from './type';
import { formatDecimal } from './util';

interface YData extends BaseNameValueObject {
  color: string;
}

interface PieChartProps {
  legend?: any;
  seriesLabel?: Function;
  options: Options;
  yData: YData[];
}

export const createPieOption = ({ legend, seriesLabel, options, yData }: PieChartProps) => {
  options = formatOptions(options);

  let textStyle = {};
  if (legend?.textStyle) {
    textStyle = legend.textStyle;
    delete legend.textStyle;
  }
  const defaultLegend = {
    show: options.showLegend,
    icon: 'circle', // 图例图标形状
    // width: 248,
    // height: 20,
    itemWidth: 8, // 图例图标宽度
    itemHeight: 8, // 图例图标高度
    itemGap: JSON.stringify(textStyle) !== '{}' ? 0 : 24, // 图例每项之间的间隔
    padding: 0, // 图例内边距，单位px，默认上下左右内边距为5
    bottom: 0,
    itemStyle: {
      borderColor: '',
      borderWidth: 0
    }, // 用来重写图例中的border样式，否则会被series的itemStyle中的配置覆盖，导致图例未选中模式下的icon变得很大（被border撑大）
    textStyle: legendStyle(textStyle), // 图例文本
    data: yData.map((item) => item.name) // 图例名称
  };
  let finalLegend = defaultLegend;
  if (legend) {
    finalLegend = Object.assign(defaultLegend, legend);
  }

  return {
    legend: finalLegend,
    tooltip: {
      trigger: 'item',
      showDelay: 0, // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
      backgroundColor: 'rgba(0, 0, 0, 0.6)', // 背景颜色
      padding: 8,
      borderRadius: 6, // 边框圆角
      borderWidth: 0, // 边框宽度
      formatter: (params: any) => {
        let itemStr = '';
        const number = formatDecimal(params.value, options.percentPrecision as number);
        const unit = '%';

        itemStr += `<div class="row" style="margin-top: 0">
          <div class="sample" style="background: ${params.color}"></div>
          <div class="name">${params.name}：</div>
          <div class="value">
            <div class="value-inner">
              <span class="unit">${unit}</span>
              <span class="number">${number}</span>
            </div>
          </div>
        </div>`;

        const str = `<div class="chart-tooltip pie">
          ${itemStr}
        </div>`;

        return str;
      }
    },
    series: [
      {
        type: 'pie',
        radius: options.radius,
        center: options.center,
        emphasis: {
          scaleSize: 5,
          label:
            options.valuePosition === 'outside'
              ? {
                show: true,
                fontFamily: 'PingFang SC, sans-serif',
                fontWeight: 400,
                fontSize: 13,
                lineHeight: 20,
                color: '#212533',
                verticalAlign: 'middle',
                formatter: seriesLabel
                  ? seriesLabel
                  : (params: any) => {
                    const res = formatSeriesLabelToPercent(params.value, options.percentPrecision as number);
                    // return `${params.name} ${res}`;
                    return params.name + ' ' + res.slice(0, -1) + '{b|%}';
                  },
                rich: {
                  a: {
                    color: '#212533',
                    fontSize: 13,
                    lineHeight: 20,
                    fontWeight: 500,
                    fontFamily: 'number, sans-serif',
                    verticalAlign: 'middle'
                  },
                  b: {
                    color: '#212533',
                    fontSize: 12,
                    lineHeight: 20,
                    fontWeight: 500,
                    fontFamily: 'PingFang SC, sans-serif',
                    verticalAlign: 'middle'
                  }
                }
              }
              : {
                show: true,
                formatter: seriesLabel
                  ? seriesLabel
                  : (params: any) => {
                    const res = formatSeriesLabelToPercent(params.value, options.percentPrecision as number);
                    return res + '\n{b|' + params.name + '}';
                  },
                fontFamily: 'PingFang SC, sans-serif',
                fontWeight: 600,
                fontSize: 18,
                lineHeight: 26,
                color: '#212533',
                rich: {
                  a: {
                    fontFamily: 'number, sans-serif',
                    fontWeight: 600,
                    fontSize: 18,
                    lineHeight: 24,
                    color: '#212533'
                  },
                  b: {
                    fontFamily: 'number, sans-serif',
                    fontWeight: 400,
                    fontSize: 12,
                    lineHeight: 18,
                    color: '#8f98b2'
                  }
                }
              }
        },
        itemStyle: {
          borderColor: '#fff', // 图形间隙颜色
          borderWidth: 1, // 图形间隙宽度
          color: (list: any) => {
            const map = new Map();
            yData.forEach((item: any) => {
              map.set(item.name, item.color);
            });
            // const colorList = yData.map((item) => item.color);
            return map.get(list.name);
          }
        },
        label: {
          show: options.valuePosition === 'center' ? false : true,
          position: options.valuePosition,
          color: '#8C8D93',
          fontSize: 13,
          lineHeight: 20,
          fontWeight: 400,
          fontFamily: 'PingFang SC, sans-serif',
          verticalAlign: 'middle',
          formatter: seriesLabel
            ? seriesLabel
            : (params: any) => {
              const res = formatSeriesLabelToPercent(params.value, options.percentPrecision as number);
              // return `${params.name} ${res}`;
              return params.name + ' ' + res.slice(0, -1) + '{b|%}';
            },
          rich: {
            a: {
              color: '#69718C',
              fontSize: 13,
              lineHeight: 20,
              fontWeight: 400,
              fontFamily: 'number, sans-serif',
              verticalAlign: 'middle'
            },
            b: {
              color: '#69718C',
              fontSize: 12,
              lineHeight: 18,
              fontWeight: 400,
              fontFamily: 'PingFang SC, sans-serif',
              verticalAlign: 'middle'
            }
          }
        },
        data: options.needSort ? [...yData].sort((a: any, b: any) => b.value - a.value) : yData
      }
    ]
  };
};
